import sys
import random

def find_rank_in_union(A, B, k):
    """Given two ordered lists A and B, find the value of the element with rank
       k in the ordered set A U B"""
    
    # Error Cases
    if len(A) + len(B) < k:
        print("The given rank was larger than the rank of the set A U B")
        return -1
    if k < 1:
        print("The given rank must be a positive integer")
        return -1
    
    # Base Cases
    if not A:
        return B[k-1]
    elif not B:
        return A[k-1]
    
    # Recursive Cases  
    if B[len(B)/2] < A[len(A)/2]:
        # swap so that A is the list with lesser mid element
        A, B = B, A 
    
    imidA = len(A)/2
    imidB = len(B)/2
    rank_barier = imidA + imidB + 1
    
    if k > rank_barier:
        return find_rank(A[(imidA+1):], B, k - (imidA+1))
    else:
        return find_rank(A, B[:imidB], k)